package com.mycompany.oj.controller;

import com.mycompany.oj.aspect.GetIp;
import com.mycompany.oj.aspect.ParseToken;
import com.mycompany.oj.entity.JsonResult;
import com.mycompany.oj.entity.ResultCode;
import com.mycompany.oj.util.JwtUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wucy
 */
@RestController
public class TestController {

    @Value("${jwt.secret}")
    private String secret;

    private JwtUtils jwtUtils = new JwtUtils();

    private String token;

    @GetIp
    @RequestMapping("/test3")
    public JsonResult test(HttpSession session) {
        session.setAttribute("username", "15161607893");
        return new JsonResult(ResultCode.SUCCESS, session.getId());
    }


    @RequestMapping("/test")
    public Object testAll(HttpServletRequest request) throws Exception {

        return jwtUtils.parseJWT(this.token,secret).get("username");

    }

    @ParseToken
    @RequestMapping("/test2")
    public Object test(HttpServletRequest request) throws Exception {

        System.out.println("1"+request.getParameter("username"));
        System.out.println("2" +request.getAttribute("username"));
        return request.getAttribute("username");

    }

    //登录页面产生token
    @RequestMapping("/login")
    public JsonResult login(@RequestParam("username") String username, @RequestParam("password") String password) throws ParseException {
        // 认证用户信息。本案例中访问静态数据。　

        Map<String, Object> map = new HashMap<String, Object>();
        Date date = new Date();
        String strDateFormat = "yyyyMMddHHmmss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String time = sdf.format(date);
        Long now = sdf.parse(time).getTime();
        map.put("username", username);
        map.put("time", now);
        String jwtToken = jwtUtils.createJWT(map, secret);
        System.out.println("成功");
        this.token = jwtToken;
        return new JsonResult(ResultCode.SUCCESS, token);

    }
}